
import axios, { type AxiosInstance, type AxiosRequestConfig, type AxiosResponse } from 'axios';
import { createPinia, setActivePinia, type Pinia } from 'pinia';
import { useUserStore } from "@/stores/user";

type ResponseData<T = any> = {
  code: number;
  message: string;
  data: T;
};

class Request {
  private instance: AxiosInstance;
  private pinia: Pinia;

  constructor(baseURL: string, pinia: Pinia) {
    this.pinia = pinia;
    this.instance = axios.create({
      baseURL,
      timeout: 10000,
      headers: {
        'Content-Type': 'application/json'
      }
    });

    this.setInterceptors();
  }

  private setInterceptors() {
    setActivePinia(this.pinia);
    this.instance.interceptors.request.use(
      (config) => {
        const userStore = useUserStore();
        if (userStore.token) {

          // config.headers.Authorization = `Bearer ${userStore.token}`;
          config.headers.set("Authorization-User", "Bearer " + userStore.token);
        }
        return config;
      },
      (error) => Promise.reject(error)
    );

    this.instance.interceptors.response.use(
      (response: AxiosResponse<ResponseData>) => {
        if (response.data.code !== 200) {
          if (response.data.code === 401) {
            // Handle token expiration or other unauthorized errors
            window.location.href = '/login'; // Redirect to login page
          }
          return Promise.reject(response);
        }
        return response.data;
      },
      (error) => {
        console.log(error, 777);
        // Unified error handling
        let message = 'Request failed';
        if (error.response) {
          switch (error.response.status) {
            case 401:
              message = 'Insufficient permissions';
              window.location.href = '/login';
              break;
            case 404:
              message = 'Resource not found';
              break;
            case 500:
              message = 'Server error';
              break;
          }
        }
        return Promise.reject(new Error(message));
      }
    );
  }

  public get<T>(url: string, params?: any, config?: AxiosRequestConfig): Promise<T> {
    return this.instance.get(url, { ...config, params });
}
public post<T>(url: string, data?: any, config?: AxiosRequestConfig): Promise<T> {
  return this.instance.post(url, data, config);
}
  public postUpload<T>(url: string, data?: any, config?: AxiosRequestConfig): Promise<T> {
    if (data instanceof FormData) {
      const mergedConfig = {
        ...config,
        headers: {
          ...config?.headers,
          'Content-Type': 'multipart/form-data'
        }
      };
      return this.instance.post(url, data, mergedConfig);
    }
    return this.instance.post(url, data, config);
  }

  public put<T>(url: string, data?: any, config?: AxiosRequestConfig): Promise<T> {
    return this.instance.put(url, data, config);
  }

  public delete<T>(url: string, config?: AxiosRequestConfig): Promise<T> {
    return this.instance.delete(url, config);
  }
}

// Initialize Pinia in main.ts and pass it here
// For now, we'll just create a temporary Pinia instance for demonstration
const pinia = createPinia();
// Configure baseURL based on the environment
const baseURL = '/';
export const request = new Request(baseURL, pinia);